package com.example.sentineldemo.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: 故我
 * Date: 2024-02-15
 * Time: 21:03
 */

/**
 * 实现一个 全局的自定义sentinel 异常
 */
@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       BlockException exception) throws Exception {
        String msg = "未知请求";
        int code = HttpStatus.TOO_MANY_REQUESTS.value(); // 状态码为 429 表示请求过多
        // 判断异常的类型
        if (exception instanceof FlowException) {
            msg = "请求被限流了";
        } else if (exception instanceof DegradeException) {
            msg = "请求被熔断了";
        } else if (exception instanceof ParamFlowException) {
            msg = "请求被热点参数限流";
        } else if (exception instanceof AuthorityException) {
            msg = "没有权限访问";
            code = HttpStatus.UNAUTHORIZED.value(); //状态码为 401 表示没有权限
        }
        response.setContentType("application/json;charset=utf-8"); //设置返回数据类型
        response.setStatus(code);
        response.getWriter().println("{ \"msg\": " + msg + "  \"code\": " + code + "  \"data\": [ ]" + "  }");
    }
}
